package com.github.zhijieqing.socket.cluster.websocket;

import com.github.zhijieqing.log.utils.JsonUtil;
import com.github.zhijieqing.socket.cluster.common.domain.SocketMsg;
import com.github.zhijieqing.socket.cluster.common.listener.MessageListener;
import com.github.zhijieqing.socket.cluster.common.storage.SessionClientStorage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.websocket.Session;

import java.util.List;

@Slf4j
public class SessionMessageListener implements MessageListener<SocketMsg> {

    private SessionClientStorage clientStorage;

    public SessionMessageListener(SessionClientStorage clientStorage) {
        this.clientStorage = clientStorage;
    }

    @Override
    public void onMessage(SocketMsg msg) {
        if(StringUtils.isEmpty(msg.getClientId())){
            return;
        }
        List<Session> sessionList = clientStorage.getSessionList(msg.getClientId());
        String text = JsonUtil.writeValueAsString(WebSocketUtils.getRealPayload(msg));
        sessionList.forEach((session) -> {
            try {
                session.getBasicRemote().sendText(text);
            } catch (Exception e) {
                log.error("给【{}】【{}】发送消息异常：", msg.getClientId(), session.getId(), e);
            }
        });
    }
}
